package com.tx.axure.tkaxureweb.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tx.axure.tkaxureweb.annotation.LoginRequired;
import com.tx.axure.tkaxureweb.constant.Constant;
import com.tx.axure.tkaxureweb.vo.ResultVoStr;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import tk.mybatis.mapper.util.StringUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Tireless
 * @version 1.0
 * @description: 拦截器
 * @date 2022/6/18 17:48
 */
public class SourceInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 反射获取方法上的LoginRequred注解
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        LoginRequired loginRequired = handlerMethod.getMethod().getAnnotation(LoginRequired.class);
        if(loginRequired != null && null==request.getSession().getAttribute(Constant.LOGIN_SESSION_KEY)){
            String requestType=request.getHeader("X-Requested-With");
            if(StringUtil.isNotEmpty(requestType)&&"XMLHttpRequest".equals(requestType)){

                // 有LoginRequired注解说明需要登录，提示用户登录
                ResultVoStr resultVoStr=new ResultVoStr();
                resultVoStr.setError(9999);
                resultVoStr.setMsg("用户未登录！");
                response.setContentType("application/json; charset=utf-8");
                ObjectMapper mapper = new ObjectMapper();
                response.getWriter().append(mapper.writeValueAsString(resultVoStr));
                return false;
            }else{
                response.sendRedirect("/login");
            }
            return false;
        }

        // 有LoginRequired注解说明需要登录，提示用户登录
//        response.setContentType("application/json; charset=utf-8");
//        response.getWriter().print("你访问的资源需要登录");
        return true;

    }
}
